package com.juhuixing.common.registrar;

import com.juhuixing.common.scanner.ClassPathAnnoEnableScanner;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述: 扫描注解中的定义的包
 * @author: 刘猛
 * @date: 2019/5/5 13:55
 **/
public class RegistrarCommon {

    public static void scanPackages(AnnotationMetadata importingClassMetadata,BeanDefinitionRegistry registry, ResourceLoader resourceLoader,Class<?> clzz){
        AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(clzz.getName()));
        ClassPathAnnoEnableScanner scanner = new ClassPathAnnoEnableScanner(registry);
        // this check is needed in Spring 3.1
        if (resourceLoader != null) {
            scanner.setResourceLoader(resourceLoader);
        }

        List<String> basePackages = new ArrayList<String>();
        for (String pkg : annoAttrs.getStringArray("basePackages")) {
            if (StringUtils.hasText(pkg)) {
                basePackages.add(pkg);
            }
        }
        scanner.doScan(StringUtils.toStringArray(basePackages));
    }
}
